package cn.darkhorse.mesadmin.controller.device;


import cn.darkhorse.alarm.dto.AlarmSettingPonitTablesDTO;
import cn.darkhorse.alarm.dto.PointTableParamsDTO;
import cn.darkhorse.alarm.service.AlarmParameterSettingsService;
import cn.darkhorse.device.dto.IotGatewayDTO;
import cn.darkhorse.device.iot.cache.IotCacheServiceI;
import cn.darkhorse.device.iot.constant.IotConstant;
import cn.darkhorse.device.pojo.IotGateway;
import cn.darkhorse.device.pojo.IotInstructParams;
import cn.darkhorse.device.pojo.IotPointTable;
import cn.darkhorse.device.service.IotGatewayService;
import cn.darkhorse.device.service.IotInstructParamsService;
import cn.darkhorse.device.service.IotPointTableService;
import cn.darkhorse.device.vo.IotGatewayVO;
import cn.darkhorse.device.vo.IotPointTableVO;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yuanjun
 * @since 2023-10-12
 */
@RestController
@RequestMapping("/device/iotGateway")
public class IotGatewayController extends BaseController {
    @Resource
    private IotGatewayService iotGatewayService;
    @Resource
    private AlarmParameterSettingsService alarmParameterSettingsService;
    @Resource
    private RedisCache redisCache;
    @Resource
    private IotCacheServiceI iotCacheService;
    @Resource
    private IotPointTableService iotPointTableService;
    @Resource
    private IotInstructParamsService instructParamsService;
    /**
     * 列表
     * @return
     */
    @RequestMapping("/list")
    public TableDataInfo listAll(IotGatewayDTO dto){
        startPage();
        TableDataInfo iotGateways = iotGatewayService.listAll(dto);
        return iotGateways;
    }
    @RequestMapping("/export")
    public AjaxResult export(IotGatewayDTO dto){
        if(StringUtils.isBlank(dto.getGatewayDeviceId())){
            return AjaxResult.error("参数为空！");
        }
        List<IotPointTable> iotPointTables = iotGatewayService.export(dto);
        ExcelUtil<IotPointTable> util = new ExcelUtil<>(IotPointTable.class);
        return util.exportExcel(iotPointTables, dto.getGatewayDeviceId()+"点表",dto.getGatewayDeviceId()+"点表");
    }
    @RequestMapping("/view")
    public AjaxResult view(Long iotId){
        if(null==iotId){
            return AjaxResult.error("参数为空！");
        }
        IotGatewayVO voList=iotGatewayService.view(iotId);
        return AjaxResult.success(voList);
    }

    /**
     * 保存
     * @param vo
     * @return
     */
    @RequestMapping("/save")
    public AjaxResult save(@RequestBody IotGatewayVO vo){
        if(null==vo){
            return AjaxResult.error("参数为空！");
        }
        Long result=iotGatewayService.saveIot(vo);
        List<IotPointTableVO> list = vo.getTableList();
        for (IotPointTableVO tableVO : list) {
            System.out.println(tableVO.getId());
        }

        List<IotPointTable> tableList = iotPointTableService.lambdaQuery().eq(IotPointTable::getGatewayDeviceId, vo.getGatewayDeviceId()).list();
        List<PointTableParamsDTO> ptParmas = new ArrayList<PointTableParamsDTO>();

        IotGateway gateway = iotGatewayService.getById(result);
        if (gateway.getIsCreateTable()){


            for (IotPointTable table : tableList) {
                PointTableParamsDTO dto = new PointTableParamsDTO();
                dto.setDisplay(1);
                dto.setPointTableId(table.getId());
                ptParmas.add(dto);
            }

            String gatewayDeviceId = alarmParameterSettingsService.saveParams(ptParmas);
            if(StringUtils.isNotBlank(gatewayDeviceId)){
                iotCacheService.addOrUpdatePointTableToCache(gatewayDeviceId);
                //修改  清除缓存
                redisCache.deleteObject(IotConstant.CACHE_MQTT_ALARM_PARAMS+gatewayDeviceId);
            }
        }
        return AjaxResult.success(result);
    }

    /**
     * 删除
     * @param iotId
     * @return
     */
    @RequestMapping("/delete")
    public AjaxResult delete(Long iotId){
        if(null==iotId){
            return AjaxResult.error("参数为空！");
        }
        IotGateway gateway = iotGatewayService.getById(iotId);
        instructParamsService.lambdaUpdate().eq(IotInstructParams::getGatewayDeviceId, gateway.getGatewayDeviceId()).remove();
        boolean result=iotGatewayService.delete(iotId);
        return AjaxResult.success(result);
    }


    /**
     * 建表
     * @param gatewayDeviceId
     * @return
     */
    @RequestMapping("/create-table")
    public AjaxResult createTable(String gatewayDeviceId){
        if(StringUtils.isBlank(gatewayDeviceId)){
            return AjaxResult.error("参数为空！");
        }

        List<IotPointTable> tableList = iotPointTableService.lambdaQuery().eq(IotPointTable::getGatewayDeviceId, gatewayDeviceId).list();

        List<PointTableParamsDTO> ptParmas = new ArrayList<PointTableParamsDTO>();

        for (IotPointTable table : tableList) {
            PointTableParamsDTO dto = new PointTableParamsDTO();
            dto.setDisplay(1);
            dto.setPointTableId(table.getId());
            ptParmas.add(dto);
        }
        alarmParameterSettingsService.saveParams(ptParmas);
        boolean result=iotGatewayService.createTable(gatewayDeviceId);

        return AjaxResult.success(result);
    }
    /**
     * 删除表
     * @param gatewayDeviceId
     * @return
     */
    @RequestMapping("/drop-table")
    public AjaxResult dropTable(String gatewayDeviceId,String code, String uuid){
        if(StringUtils.isBlank(gatewayDeviceId)){
            return AjaxResult.error("参数为空！");
        }
        boolean result=false;
        if(iotGatewayService.validateCaptcha(code,uuid)){
            result=iotGatewayService.dropTable(gatewayDeviceId);
        }
        return AjaxResult.success(result);
    }

    /**
     * 克隆设备
     * @return
     */
    @RequestMapping("/clone-device")
    public AjaxResult cloneDevice(Long iotId){
        //IotGatewayVO vo=iotGatewayService.cloneDevice(gatewayDeviceId);
        IotGatewayVO vo=iotGatewayService.view(iotId);
        return AjaxResult.success(vo);
    }

    /**
     * 删除
     * @param gatewayDeviceId
     * @return
     */
    @RequestMapping("/has-table")
    public AjaxResult hasTable(String gatewayDeviceId){
        if(StringUtils.isBlank(gatewayDeviceId)){
            return AjaxResult.error("参数为空！");
        }
        boolean result=iotGatewayService.hasTable(gatewayDeviceId);
        return AjaxResult.success(result);
    }
    /**
     * 生成验证码
     * @return
     */
    @RequestMapping("/validate-captcha")
    public AjaxResult validateCaptcha(String code, String uuid){
        boolean result =iotGatewayService.validateCaptcha(code,uuid);
        return AjaxResult.success(result);
    }


    /**
     * 设备参数信息  根据网关ID
     * @param gatewayDeviceId
     * @param paramName  参数名称
     * @return
     */
    @RequestMapping("/device-params")
    public TableDataInfo deviceParamsByGaDeId(String gatewayDeviceId,String paramName){
        if(StringUtils.isBlank(gatewayDeviceId)){
            return new TableDataInfo();
        }
        List<IotPointTable> iotPointTables = iotGatewayService.deviceParamsByGaDeId(gatewayDeviceId,paramName);
        List<AlarmSettingPonitTablesDTO> settingPointTables = alarmParameterSettingsService.settingPonitTableList(null,null,null);
        if(!settingPointTables.isEmpty()){
            Iterator<IotPointTable> iterator = iotPointTables.iterator();
            while (iterator.hasNext()){
                IotPointTable next = iterator.next();
                for(AlarmSettingPonitTablesDTO ipt:settingPointTables){
                    if(next.getId().equals(ipt.getIptId())){
                        iterator.remove();
                        break;
                    }
                }
            }
        }
        return getDataTable(iotPointTables);
    }
}

